package goComfyuiApi

import (
	"bytes"
	"encoding/json"
	"mime/multipart"
	"net/http"
)

// 上传图片
func ApiUploadImage(comfyuiUrl string, imageData []byte, filename string) (string, error) {
	var buf bytes.Buffer
	writer := multipart.NewWriter(&buf) // 使用指定文件名创建表单文件字段
	part, err := writer.CreateFormFile("image", filename)
	if err != nil {
		return "", err
	} // 直接将字节数据写入part
	if _, err = part.Write(imageData); err != nil {
		return "", err
	}
	writer.Close() // 后续HTTP请求部分保持不变

	url := genComfyUIApiUrl(comfyuiUrl, "upload/image")
	resp, err := http.Post(url, writer.FormDataContentType(), &buf)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	var result struct {
		Name string `json:"name"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		return "", err
	}
	return result.Name, nil
}
